package logic

import (
	"context"
	"encoding/json"
	"time"
	"wechats/model/cache"
	"wechats/model/mysql"

	"wechats/wechatrpc/internal/svc"
	"wechats/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type MomentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMomentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MomentListLogic {
	return &MomentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MomentListLogic) MomentList(in *wechatrpc.MomentListRequest) (*wechatrpc.MomentListResponse, error) {
	// todo: add your logic here and delete this line

	var personal []mysql.Personal
	result, _ := cache.Rdb.Get(l.ctx, "MomentList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&personal)
		marshal, _ := json.Marshal(personal)

		cache.Rdb.Set(l.ctx, "MomentList", marshal, time.Minute*3)
	} else {
		json.Unmarshal([]byte(result), &personal)
	}

	var personalList []*wechatrpc.MomentList
	for _, m := range personal {
		list := wechatrpc.MomentList{
			Id:      int64(m.ID),
			Image:   m.Image,
			Name:    m.Name,
			Hao:     m.Hao,
			Address: m.Address,
		}
		personalList = append(personalList, &list)
	}
	return &wechatrpc.MomentListResponse{
		List: personalList,
	}, nil
}
